/**
 * Copyright (c) qzsoft All rights reserved.
 * <p>
 * qzsoft.cn
 * <p>
 * 版权所有，侵权必究！
 */

package com.qzsoft.system.modules.permission.dept.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.qzsoft.jeemis.common.utils.ConvertUtils;
import com.qzsoft.system.modules.permission.dept.dao.SysDeptMapper;
import com.qzsoft.system.modules.permission.dept.dto.SysDeptDTO;
import com.qzsoft.system.modules.permission.dept.dto.SysDeptTreeDTO;
import com.qzsoft.system.modules.permission.dept.dto.SysDeptTreeDto2;
import com.qzsoft.system.modules.permission.dept.excel.SysDeptExcel;
import com.qzsoft.system.modules.permission.dept.excel.SysDeptExcel2;
import com.qzsoft.system.modules.permission.dept.service.SysDeptService;
import com.qzsoft.system.modules.permission.user.service.SysUserService;
import com.qzsoft.system.repository.sys.dao.SysDeptDao;
import com.qzsoft.system.repository.sys.entity.SysDeptEntity;
import com.qzsoft.jeemis.common.annotation.LogOperation;
import com.qzsoft.jeemis.common.utils.ExcelDictHandlerImpl;
import com.qzsoft.jeemis.common.utils.ExcelUtils;
import com.qzsoft.jeemis.common.utils.Result;
import com.qzsoft.jeemis.common.validator.AssertUtils;
import com.qzsoft.jeemis.common.validator.ValidatorUtils;
import com.qzsoft.jeemis.common.validator.group.AddGroup;
import com.qzsoft.jeemis.common.validator.group.DefaultGroup;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.lang.reflect.Field;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;

/**
 * 部门管理
 */
@RestController
@RequestMapping("/api/sys/dept")
@Api(tags = "部门管理")
public class SysDeptController {
    @Resource
    private SysDeptService sysDeptService;
    @Autowired
    private SysUserService sysUserService;
    @Autowired
    SysDeptDao sysDeptDao;
    @Autowired
    SysDeptMapper deptMapper;

    /*************** 2020-10-10 16:10:00 增加列表分页方法 孙文文  MOD  START ***************/
    @GetMapping("page")
    @ApiOperation("列表分页")
    @RequiresPermissions("sys:dept:list")
    public Result<IPage<SysDeptEntity>> page(Page page, SysDeptEntity sysDeptEntity) {
        IPage<SysDeptEntity> list = sysDeptService.list(page, sysDeptEntity);
        return new Result<IPage<SysDeptEntity>>().ok(list);
    }
    /*************** 2020-10-10 16:10:00 增加列表分页方法 孙文文  MOD  END ***************/
    /*************** 2020-10-10 16:59:00 增加getDeptlist方法 孙文文  MOD  START ***************/
    @GetMapping("getDeptlist")
    @ApiOperation("列表")
    public Result<List<Map<String, Object>>> getDeptlist(String pcode) throws IllegalAccessException {
        QueryWrapper<SysDeptEntity> query = new QueryWrapper<>();
       // query.eq("pkid", pcode).orderByAsc("sort");
        List<SysDeptEntity> entityList = sysDeptDao.selectList(query);
        List<Map<String, Object>> result = new ArrayList<Map<String, Object>>();
        for (SysDeptEntity deptEntity : entityList) {
            String code = deptEntity.getId();
            query = new QueryWrapper<>();
//            query.eq("del_flg", 0);
//            query.eq("pkid", code);
            int count = sysDeptDao.selectCount(query);

            Map<String, Object> map = objectToMap(deptEntity);
            map.put("checked", false);
            map.put("count", count);
            result.add(map);
        }
        return new Result<List<Map<String, Object>>>().ok(result);
    }

    /*************** 2020-10-10 16:10:00 增加getDeptlist方法 孙文文  MOD  END ***************/

    /*************** 2020-10-10 17:10:00 增加getAllDeptList方法 孙文文  MOD  START ***************/

    @GetMapping("list/all")
    @ApiOperation("列表")
    public Result<List<SysDeptEntity>> getAllDeptList(String pid) {
        QueryWrapper<SysDeptEntity> query = new QueryWrapper<>();
        query.select("id", "id", "pid", "name", "type");
        //字段名进行相应的修改
        if (StringUtils.isNotBlank(pid)) {
            query.likeLeft("pid", pid).orderByAsc("sort");
        } else {
            query.orderByAsc("sort");
        }
        List<SysDeptEntity> sysDeptEntityList = sysDeptDao.selectList(query);
        return new Result<List<SysDeptEntity>>().ok(sysDeptEntityList);
    }

    /*************** 2020-10-10 17:10:00 增加getAllDeptList方法 孙文文  MOD  END ***************/

    /*************** 2020-10-10 17:10:00 增加getDeptListByPcode方法 孙文文  MOD  START ***************/
    @GetMapping("getDeptListByPcode")
    @ApiOperation("列表")
    public Result<List<SysDeptTreeDTO>> getDeptListByPcode(String pcode, String deptName) throws IllegalAccessException {
        QueryWrapper<SysDeptEntity> query = new QueryWrapper<>();
        query.eq("del_flg", 0);
        if (StringUtils.isNotBlank(deptName)) {
            query.like("name", deptName).orderByAsc("sort", "code");
        } else {
            if (StringUtils.isNotBlank(pcode)) {
                query.eq("pcode", pcode).orderByAsc("sort");
            } else {
                query.and(wrapper -> wrapper.isNull("pcode").or().eq("pcode", "")).orderByAsc("sort");
            }
        }
        List<SysDeptEntity> entityList = sysDeptDao.selectList(query);
        List<SysDeptTreeDTO> result = ConvertUtils.sourceToTarget(entityList, SysDeptTreeDTO.class);
        for (SysDeptTreeDTO sysDeptTreeDTOTemp : result) {
            String code = sysDeptTreeDTOTemp.getCode();
            query = new QueryWrapper<>();
            query.eq("del_flg", 0);
            query.eq("pcode", code);
            sysDeptTreeDTOTemp.setChildCount(sysDeptDao.selectCount(query));
        }
        return new Result<List<SysDeptTreeDTO>>().ok(result);
    }

    /*************** 2020-10-10 17:10:00 增加getDeptListByPcode方法 孙文文  MOD  END ***************/

    /*************** 2020-10-10 17:10:00 此方法以中台的业务逻辑方法为准 孙文文  MOD  START ***************/
    /**
     * 根据组织名称查询组织列表
     *
     * @param deptName 组织名称
     * @return Result<List < Map < String, Object>>> 组织列表
     */
    @GetMapping("get_dept_list_by_name")
    @ApiOperation("组织机构名称查询")
    public Result<List<Map<String, Object>>> getDeptListByName(String deptName) {

        List<Map<String, Object>> result = sysDeptService.getDeptListByName(deptName);
        return new Result<List<Map<String, Object>>>().ok(result);
    }
    /*************** 2020-10-10 17:10:00 此方法以中台的业务逻辑方法为准 孙文文  MOD  END ***************/


    /*************** 2020-10-10 16:59:00 增加objectToMap方法 孙文文  MOD  START ***************/
    public static Map<String, Object> objectToMap(Object obj) throws IllegalAccessException {
        Map<String, Object> map = new HashMap<String, Object>();
        Class<?> clazz = obj.getClass();
        for (Field field : clazz.getDeclaredFields()) {
            field.setAccessible(true);
            String fieldName = field.getName();
            Object value = field.get(obj);
            map.put(fieldName, value);
        }
        return map;
    }

    /*************** 2020-10-10 16:59:00 增加objectToMap方法 孙文文  MOD  END ***************/

    @GetMapping("get")
    @ApiOperation("信息")
    @RequiresPermissions("sys:dept:info")
    public Result<SysDeptEntity> get(String pkId) {
        SysDeptEntity data = sysDeptService.get(pkId);

        return new Result<SysDeptEntity>().ok(data);
    }

    @PostMapping("save")
    @ApiOperation("保存")
    @LogOperation("保存")
    @RequiresPermissions("sys:dept:save")
    public Result<SysDeptEntity> save(@RequestBody SysDeptEntity dto) {
        //效验数据
        ValidatorUtils.validateEntity(dto, AddGroup.class, DefaultGroup.class);
        return new Result<SysDeptEntity>().ok(sysDeptService.saveDept(dto));
        /*************** 2020-10-10 17:22:00 中台没有假删除逻辑  所以无更新操作 孙文文 注释以作说明 ***************/
    }

    @PostMapping("delete")
    @ApiOperation("删除")
    @LogOperation("删除")
    @RequiresPermissions("sys:dept:delete")
    public Result delete(String pkId) {
        //效验数据
        AssertUtils.isNull(pkId, "pkId");

        sysDeptService.delete(pkId);

        return new Result();
    }

    @PostMapping("sort")
    @ApiOperation("排序")
    @LogOperation("排序")
    @RequiresPermissions("sys:dept:save")
    public Result sort(String pkId1, String pkId2) {
        //效验数据
        AssertUtils.isNull(pkId1, "pkId1");
        AssertUtils.isNull(pkId2, "pkId2");
        sysDeptService.saveDeptSort(pkId1, pkId2);
        return new Result();
    }


    @GetMapping("export")
    @ApiOperation("导出")
    @LogOperation("导出")
    @RequiresPermissions("sys:dept:list")
    public void export(HttpServletResponse response) throws Exception {
        List<SysDeptExcel> list = sysDeptService.listAll();
        ExcelUtils.exportExcelToTarget(response, "机构列表导出", list, SysDeptExcel.class);
    }

    @GetMapping("export2")
    @ApiOperation("导出")
    @LogOperation("导出")
    @RequiresPermissions("sys:dept:list")
    public void export2(HttpServletResponse response) throws Exception {
        List<SysDeptEntity> list = sysDeptService.listAll2();
        ExcelUtils.exportExcelToTarget(response, "机构列表导出", "机构列表", "机构", list, SysDeptExcel2.class, new ExcelDictHandlerImpl());
    }

    @GetMapping("list")
    @ApiOperation("列表")
    @RequiresPermissions("sys:dept:list")
    public Result<List<SysDeptEntity>> list(String pId) {
        List<SysDeptEntity> list = sysDeptService.list(pId);

        return new Result<List<SysDeptEntity>>().ok(list);
    }

    @GetMapping("out_list")
    @ApiOperation("列表")
    @RequiresPermissions("sys:dept:list")
    public Result<List<SysDeptEntity>> outList(String pId) {
        List<SysDeptEntity> list = sysDeptService.outList(pId);

        return new Result<List<SysDeptEntity>>().ok(list);
    }

    /*************** 2020-10-10 17:10:00 增加getBreadCrumbsList方法 孙文文  ADD  START ***************/
    @GetMapping("breadcrumbslist")
    @ApiOperation("面包屑list")
    public Result<List<SysDeptEntity>> getBreadCrumbsList(SysDeptDTO sysDeptDTO) {
        sysDeptDTO.setSysDeptEntityList(new ArrayList<SysDeptEntity>());
        List<SysDeptEntity> data = sysDeptService.getBreadCrumbsList(sysDeptDTO);

        return new Result<List<SysDeptEntity>>().ok(data);
    }
    /*************** 2020-10-10 17:10:00 增加getBreadCrumbsList方法 孙文文  ADD  END ***************/

    /*************** 2020-10-10 17:10:00 增加getfullpinyin方法 孙文文  ADD  START ***************/
    @PostMapping("getfullpinyin")
    @ApiOperation("列表")
    public String getfullpinyin(String hanzi) {
        if (StringUtils.isNotBlank(hanzi)) {
            return sysDeptService.getfullpinyin(hanzi);
        } else {
            return "";
        }
    }
    /*************** 2020-10-10 17:10:00 增加getfullpinyin方法 孙文文  ADD  END ***************/

    /*************** 2020-10-10 17:10:00 增加chooseDeptUser方法 孙文文  ADD  START ***************/

    @GetMapping("chooseDeptUser")
    @ApiOperation("列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "username", value = "用户名", paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "id", value = "组织机构id", paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "flag", value = "是否是按照名称模糊查询", paramType = "query", dataType = "String")
    })
    public Result<List<Map<String, Object>>> chooseDeptUser(String userName, String id, String flag) throws IllegalAccessException {
        QueryWrapper<SysDeptEntity> query = new QueryWrapper<>();
        query.eq("pid", id).orderByAsc("sort");

        List<SysDeptEntity> entityList = sysDeptDao.selectList(query);
        Map<String, Object> paras = new HashMap<String, Object>();

        List<Map<String, Object>> result = new ArrayList<Map<String, Object>>();
        if (flag.equals("1")) {
            //添加组织信息
            for (SysDeptEntity deptEntity : entityList) {
                //获取组织人员信息
                int count = 0;
                paras.put("dept_code", "");
                paras.put("username", "");
                List<Map<String, Object>> userList = deptMapper.getDeptUser(paras);
                for (Map<String, Object> deptmap : userList) {
                    if (deptmap.get("dept_code").equals(deptEntity.getId())) {
                        count = ((Long) deptmap.get("count")).intValue();
                    }
                }

                //添加组织详细信息
                Map<String, Object> map = new HashMap<String, Object>();
                map.put("id", deptEntity.getId());
                map.put("name", deptEntity.getName());
                map.put("realName", null);
                map.put("checked", false);
                map.put("hasDept", deptEntity.getHasLeaf().equals("0") ? true : false);
                map.put("count", userList.size());
                map.put("headUrl", null);
                map.put("isDept", true);
                result.add(map);
            }
        }

        //添加组织人员信息
        if (!StringUtils.isBlank(userName) || !StringUtils.isBlank(id)) {
            paras.put("dept_code", id);
            paras.put("username", userName);
            List<Map<String, Object>> userList = deptMapper.getUserInfo(paras);
            for (Map<String, Object> userMap : userList) {
                userMap.put("hasDept", false);
                userMap.put("headUrl", null);
                userMap.put("isDept", false);
                userMap.put("count", 0);
                userMap.put("checked", false);
                result.add(userMap);
            }
        }
        return new Result<List<Map<String, Object>>>().ok(result);
    }
    /*************** 2020-10-10 17:10:00 增加chooseDeptUser方法 孙文文  ADD  END ***************/

    /*************** 2020-10-10 17:10:00 增加getcheckerrcode方法 孙文文  ADD  START ***************/

    @PostMapping("getcheckerrcode")
    @ApiOperation("保存机构数据时验证")
    public Result<SysDeptDTO> getcheckerrcode(@RequestBody SysDeptDTO dto) {
        return new Result<SysDeptDTO>().ok(sysDeptService.getCheckErrCode(dto));
    }
    /*************** 2020-10-10 17:10:00 增加getcheckerrcode方法 孙文文  ADD  END ***************/

    //region 赵爱增加 取单位列表 实现前端选择单位 2020-8-28

    /**
     * 根据父级单位ID查询单位列表
     *
     * @param pId 父级单位ID
     * @return Result 单位列表
     */
    @GetMapping("get_dept_list")
    @ApiOperation("取单位列表")
    public Result<List<Map<String, Object>>> getDeptList(String pId) {
        List<Map<String, Object>> result = sysDeptService.getDeptList(pId);
        return new Result<List<Map<String, Object>>>().ok(result);
    }
   

    /**
     * 获取已选择组织机构
     *
     * @param ids 已选择组织机构ID
     * @return Result<List < Map < String, Object>>> 组织列表
     */
    @GetMapping("get_selected_dept_list")
    @ApiOperation("获取已选择组织机构")
    public Result<List<Map<String, Object>>> getSelectedDeptList(String ids) {

        List<Map<String, Object>> result = sysDeptService.getSelectedDeptList(ids);
        return new Result<List<Map<String, Object>>>().ok(result);
    }

    //endregion

    @GetMapping("get_dept_tree")
    @ApiOperation(value = "获取指定机构下的树结构")
    public Result getDeptTree(@RequestParam String pid) {
        List<SysDeptTreeDto2> list = sysDeptService.getDeptTree(pid);
        return new Result().ok(list);
    }



}